import router from "@/router";
import { useToken } from "@/stores/token";
import type { ResponseResult } from "@/types/common";
import axios, { AxiosError, type AxiosResponse, type InternalAxiosRequestConfig } from "axios";
import { ElMessage } from "element-plus";

const instance = axios.create({
  baseURL:import.meta.env.VUE_APP_BASE_URL,
  timeout:5000
})

// 请求拦截器
instance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  // 注入token
  const store = useToken()
  if (store.getToken()) {
    config.headers.Authorization = store.getToken()
  }
  return config
}, error => Promise.reject(error))

// 响应拦截器
instance.interceptors.response.use((response: AxiosResponse) => {
  const result = response.data
  // 判断业务状态码
  if (result.code === 10000) {
    return response.data.data // 返回正常数据
  }
  ElMessage({
    message: result.msg,
    type: 'error'
  })
  return Promise.reject(new Error(result.msg))

}, (error: AxiosError) => {
  if (error.status === 401) {
    // token失效
    const store = useToken()
    store.removeToken() // 删除token
    router.push("/login") // 跳转到登录页
  } else {
    // bug 需要指定具体类型
    const res = error.response?.data as ResponseResult
    ElMessage({
      message: res.msg,
      type: "error"
    })
  }
  return Promise.reject(error)
})

export class RequestAxios {
  static get<T> (url:string,params?:object) {
    return instance.get<null,T>(url,{ params })
  }
  static post<T> (url:string,data?:object) {
    return instance.post<null,T>(url,data)
  }
  static put<T> (url:string,data?:object) {
    return instance.put<null,T>(url,data)
  }
  static delete<T> (url:string,params?:object) {
    return instance.delete<null,T>(url,{ params })
  }
}